import { reqShopCartList,reqShopSelect,reqDeleteCart} from '@/api/'
export default {
    state: () => ({
        shopCartList:[]
    }),
    getters:{
        cartInfoList(state){
            if(state.shopCartList[0]){
                return state.shopCartList[0].cartInfoList
            }
            return []
        }
    },
    mutations:{
        GETSHOPCART(state,data){
            state.shopCartList=data
        }
    },
    //请求shopcart相关数据
    actions: {
        //获取购物车
       async getShopCart(context){
           try{
            const shopCart= await reqShopCartList()
            if(shopCart.code===200){
                context.commit('GETSHOPCART',shopCart.data)
            }
           
           }catch(error){

           }
           
        },
         //获取切换选择购物车
        async switchSelect(_,data){
            try{
            
                const isSelect= await reqShopSelect(data.skuID,data.isChecked)

                if(isSelect.code===200){
                    return 'ok'
                }else{
                    return Promise.reject(new Error('更改失败'))
                }
            }catch(error){
                return Promise.reject(new Error('fail'))
            }
        },
        async switchSelectAll({dispatch,state},isChecked){
            let promises=[]
           
            try{
                state.shopCartList[0].cartInfoList.forEach(item => {
                
                    const  promise= dispatch('switchSelect',{skuID:item.skuId,isChecked})
                    promises.push(promise)
                });
                return  Promise.all(promises)
            }catch(error){
                return Promise.reject(new Error('fail'))
            }
        },
        async deleteCart({},skuId){
            try{
              const isSuccess = await reqDeleteCart(skuId)
              if(isSuccess.code===200){
                 return 'ok'
              }else{
                    return Promise.reject(new Error('删除失败'))
              }
            }catch(error){
                return Promise.reject(new Error('fail'))
            }
            
        },
        async deleteSelectCart({dispatch,state}){
            let promises=[]
            try{
                state.shopCartList[0].cartInfoList.forEach(item => {
                    if(item.isChecked){
                      const  promise= dispatch('deleteCart',item.skuId)
                      promises.push(promise)
                    }
                });
                return  Promise.all(promises)
            }catch(error){
                return Promise.reject(new Error('fail'))
            }
        }
    }
}